#include "stdafx.h"
#include "Utility.h"

CString logFilePath;
FILE* Utility::m_pFileHandle = NULL;
CRITICAL_SECTION Utility::m_Critical;

Utility gUtility;

Utility::Utility()
{
	InitializeCriticalSection(&m_Critical);
}

Utility::~Utility()
{
	DeleteCriticalSection(&m_Critical);
	if(m_pFileHandle) fclose(m_pFileHandle);
}

void Utility::PrintLog(CString str)
{
	SYSTEMTIME sysTime;
	GetLocalTime(&sysTime);
	CString strFilePath,strlog;

	EnterCriticalSection(&m_Critical);

	strFilePath.Format(_T("log\\ImageLab_%.4u%.2u%.2u.log"), sysTime.wYear, sysTime.wMonth, sysTime.wDay);
	if(strFilePath.CompareNoCase(logFilePath) != 0)
	{
		if(m_pFileHandle)
		{
			fclose(m_pFileHandle);
			Sleep(10);
		}
		logFilePath = strFilePath;
		m_pFileHandle=_wfopen(logFilePath, _T("a+"));
	}
	strlog.Format(_T("[%.4u/%.2u/%.2u %.2u:%.2u:%.2u:%u] %s"), sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds, str);
	//strlog.Format(_T("%s"),str);
	if(m_pFileHandle)
	{
		fwprintf(m_pFileHandle, _T("%s\n"), strlog);
		fflush(m_pFileHandle);
	}

	LeaveCriticalSection(&m_Critical);
}

CString Utility::PrintTS()
{
	SYSTEMTIME sysTime;
	GetLocalTime(&sysTime);
	CString str;
	str.Format(_T("%.4u-%.2u-%.2uT%.2u:%.2u:%.2u+08:00"), sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
	return str;
}

CString Utility::PrintTSID()
{
	SYSTEMTIME sysTime;
	GetLocalTime(&sysTime);
	CString str;
	str.Format(_T("%.4u%.2u%.2u%.2u%.2u%.2u%u"), sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond,sysTime.wMilliseconds);
	return str;
}


CString FindExtension(const CString& name)
{
	int len = name.GetLength();
	int i;
	for (i = len-1; i >= 0; i--){
		if (name[i] == '.'){
			return name.Mid(i+1);
		}
	}
	return CString(_T(""));
}

CString FindFileDir(const CString& name)
{
	int len = name.GetLength();
	int i;
	for (i = len-1; i >= 0; i--){
		if (name[i] == '\\'){
			return name.Left(i+1);
		}
	}
	return CString(_T(""));
}

CString FindFileName(const CString& name)
{
	int len = name.GetLength();
	int i;
	for (i = len-1; i >= 0; i--){
		if (name[i] == '\\'){
			return name.Right(len-i-1);
		}
	}
	return CString(_T(""));
}

CString RemoveExtension(const CString& name)
{
	int len = name.GetLength();
	int i;
	for (i = len-1; i >= 0; i--){
		if (name[i] == '.'){
			return name.Mid(0,i);
		}
	}
	return name;
}